//
//  SEExamineOrderViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/9.
//

import UIKit

enum SEExamineOrderViewControllerFromType {
    case examineOrderList
    case examineReserve
}

class SEExamineOrderViewController: SEBaseViewController {

    @IBOutlet weak var payView: SEConfirmReservePayView! {
        didSet {
            payView.isHidden = true
            payView.delegate = self
        }
    }

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.tableFooterView = UIView()
            tableView.register(UINib(nibName: SEExamineOrderHospitalCell.className, bundle: nil), forCellReuseIdentifier: SEExamineOrderHospitalCell.reuseId)
            tableView.register(UINib(nibName: SEExamineOrderEyeTypeCell.className, bundle: nil), forCellReuseIdentifier: SEExamineOrderEyeTypeCell.reuseId)
            tableView.register(UINib(nibName: SEExamineOrderProjectCell.className, bundle: nil), forCellReuseIdentifier: SEExamineOrderProjectCell.reuseId)
        }
    }

    var viewModel = SEExamineDetailViewModel()
    var paySuccessHandler: (() -> Void)?

    init(with applyFormId: String, fromType: SEExamineOrderViewControllerFromType) {
        viewModel.applyFormId = applyFormId
        viewModel.fromType = fromType
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "检查预约"
        requestExamineDetail()
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()
        viewModel.updateData = { [weak self] (status) in
            switch status {
            case .success:
                self?.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestExamineDetail), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.payHandler = { [weak self] (status) in
            switch status {
            case .success:
                self?.paySuccess()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestPayExamine), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    lazy var viewForHeaderSectionOne: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.background
        let imageView = UIImageView(image: #imageLiteral(resourceName: "registration_detail_line_image"))
        imageView.contentMode = .scaleToFill
        view.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.margins.equalToSuperview()
        }
        return view
    }()

    lazy var viewForHeaderSectionTwo: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        let label = UILabel()
        label.text = "检查项目"
        label.textColor = Asset.textDark.color
        label.font = UIFont.regular(14)
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }()

    lazy var viewForHeaderSectionThree: UIView = {
        let view = UIView()
        let imageView = UIImageView(image: #imageLiteral(resourceName: "registration_detail_line_image"))
        imageView.contentMode = .scaleToFill
        view.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.margins.equalToSuperview()
        }
        return view
    }()

    private func reloadData() {
        tableView.isHidden = false
        tableView.reloadData()
        payView.isHidden = false
        payView.updateView(with: viewModel.payViewModel)
    }

    private func paySuccess() {
        switch viewModel.fromType {
        case .examineOrderList:
            SEHUD.show(message: "支付成功")
            self.paySuccessHandler?()
            navigationController?.popViewController(animated: true)
        case .examineReserve:
            pushExamineOrderListViewController()
        }
    }

    private func pushExamineOrderListViewController() {
        let vc = SEOrderExamineViewController(with: .payexamine)
        vc.title = "检查订单"
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

// MARK: - UITableViewDataSource, UITableViewDelegate
extension SEExamineOrderViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewModel.numberOfRowsInSectionForWaitPay(section: section)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSectionForWaitPay
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineOrderHospitalCell.reuseId, for: indexPath) as! SEExamineOrderHospitalCell
            cell.updateCell(viewModel)
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineOrderEyeTypeCell.reuseId, for: indexPath) as! SEExamineOrderEyeTypeCell
            cell.updateCell(viewModel.eyeTypeCellModel(indexPath: indexPath))
            return cell
        }
        if indexPath.section == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineOrderProjectCell.reuseId, for: indexPath) as! SEExamineOrderProjectCell
            cell.updateCell(viewModel.checkItem(indexPath: indexPath))
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEExamineOrderEyeTypeCell.reuseId, for: indexPath) as! SEExamineOrderEyeTypeCell
            cell.titleMemoView.memoLabel.font = UIFont.regular(14)
            cell.updateCell(viewModel.eyeTypeCellModel(indexPath: indexPath))
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 1:
            return viewForHeaderSectionOne
        case 2:
            return viewForHeaderSectionTwo
        case 3:
            return viewForHeaderSectionThree
        default:
            return UIView()
        }

    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        viewModel.heightForHeaderForWaitPay(section: section)
    }

}

// MARK: - SEConfirmReservePayViewDelegate

extension SEExamineOrderViewController: SEConfirmReservePayViewDelegate {
    func confirmReservePayViewBtnAction(_ payView: SEConfirmReservePayView, with actionType: SEConfirmReservePayViewActionType) {
        switch actionType {
        case .pay:
            self.requestPayExamine()
        case .agree:
            viewModel.isAgree = payView.agreeBtn.isSelected
            reloadData()
        case .showInfo:
            showAgreementView()
        }
    }

    private func showAgreementView() {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                        agreementView.show(type: .informedLetter)
    }
}

// MARK: - APIRequest

extension SEExamineOrderViewController {
    @objc func requestExamineDetail() {
        viewModel.requestExamineDetail()
    }

    @objc func requestPayExamine() {
        viewModel.requestPayExamine()
    }
}
